var app=angular.module('showApp',['ngSanitize']),
	rptCycleId = UI.getParameterByName('rptCycleId'),
	moduleIds = UI.getParameterByName('moduleId'),
	rptName = UI.getParameterByName('rptName'),
	colorS = ['#3EBFBE', '#FFB553', '#DB5D4F', '#8078D7', '#4D5361', '#949FB2', '#ac5348', '#4591aa', '#716082','#52679b','#94975e','#016976','#cea350','#567832','#a85d31'],//提供饼图不同部分的颜色
	titleS = {
		'font-size': '20px',
//	    'font-weight': 'bold',
//	    'color':'#666',
	    'opacity':0,
		'line-height': '40px',
		'font-family': 'SimHei,Microsoft Yahei,Helvetica,Arial,sans-serif'
	};
var moduleIdArr = [], moudleElement=[];
var moduleIdArr = moduleIds.split(',');

$.each(moduleIdArr,function(index,value){
	$(".headerTitle h2").text(rptName);
	if(rptCycleId==1){//日报
		if(value==13||value==14||value==15||value==16||value==18||value==17||value==19){
			moudleElement[index] = $(".summary_txt[data-i="+value+"]").clone();
			moudleElement[index].attr("ng-show","showDailyArr["+index+"]");
			moudleElement[index].children().eq(0).attr("ng-bind","reportData["+index+"].name");
			if(value==13||value==15||value==18||value==17||value==19){
				moudleElement[index].children().eq(1).attr("ng-bind","reportData["+index+"].text");
				if(value==15||value==18||value==17||value==19){
					moudleElement[index].children().eq(2).children().eq(0).children().eq(1).attr("ng-repeat","sensitive in sensitiveInfoList["+index+"]");
				}
			}else if(value==14){
				moudleElement[index].children().eq(1).children().eq(0).children().eq(1).attr("ng-repeat","sensitive in sensitiveInfoList["+index+"]");
			}else if(value==16){
				moudleElement[index].children().eq(1).attr("ng-bind-html","reportData["+index+"].text");
				moudleElement[index].children().eq(2).attr("ng-repeat","news in sensitiveInfoList["+index+"]");
			}
			$(".summary").append(moudleElement[index]);
		}
	}else if(rptCycleId==2){//周报
		if(value==1||value==5||value==8||value==9||value==10||value==11||value==12){
			if(value==1){
				moudleElement[index] = $(".summary_txt[data-i="+value+"]").clone();
				moudleElement[index].attr("ng-show","showWeeklyArr["+index+"]");
				moudleElement[index].children().eq(0).attr("ng-bind","reportData["+index+"].name");
				moudleElement[index].children().eq(1).attr("ng-bind","reportData["+index+"].text");
			}else if(value==5||value==8||value==9||value==10||value==11||value==12){
				moudleElement[index] = $(".summary_txt[data-i="+value+"]").clone();
				moudleElement[index].attr("ng-show","showWeeklyArr["+index+"]");
				moudleElement[index].children().eq(0).attr("ng-bind","reportData["+index+"].name");
				moudleElement[index].children().eq(1).attr({"data":"{{vm."+value+".data}}","opt":"{{vm."+value+".opt}}"});
			}
			$(".summary").append(moudleElement[index]);
		}
	}else if(rptCycleId==3){//月报
		if(value==1||value==2||value==3||value==4||value==5||value==6||value==7||value==8){
			if(value==1){
				moudleElement[index] = $(".summary_txt[data-i="+value+"]").clone();
				moudleElement[index].attr("ng-show","showMonthlyArr["+index+"]");
				moudleElement[index].children().eq(0).attr("ng-bind","reportData["+index+"].name");
				moudleElement[index].children().eq(1).attr("ng-bind","reportData["+index+"].text");
			}else if(value==2||value==3||value==4||value==5||value==6||value==7||value==8){
				moudleElement[index] = $(".summary_txt[data-i="+value+"]").clone();
				moudleElement[index].attr("ng-show","showMonthlyArr["+index+"]");
				moudleElement[index].children().eq(0).attr("ng-bind","reportData["+index+"].name");
				moudleElement[index].children().eq(1).attr({"data":"{{vm."+value+".data}}","opt":"{{vm."+value+".opt}}"});
			}
			$(".summary").append(moudleElement[index]);
		}
	}
	
});

app.config(function($httpProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
 
    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
        /**
         * The workhorse; converts an object to x-www-form-urlencoded serialization.
         * @param {Object} obj
         * @return {String}
         */
        var param = function(obj) {
            var query = '';
            var name, value, fullSubName, subName, subValue, innerObj, i;
            for (name in obj) {
                value = obj[name];
                if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value instanceof Object) {
                    for (subName in value) {
                        subValue = value[subName];
                        fullSubName = name + '[' + subName + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value !== undefined && value !== null) {
                    query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                }
            }
            return query.length ? query.substr(0, query.length - 1) : query;
        };
        return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
    }];
});

app.controller('showController',function($scope,$http){
	var vm = $scope.vm = {};
	function ck_call(obj) {
		if(obj.returnCode != 10000) {
			return 0;
		}
		return 1;
	}
	function time_month_day(time) {
		var mdTime = time.split('-');
		return parseInt(mdTime[1]) + '月' + parseInt(mdTime[2]) + '日';
	};
	
	$scope.reportData = [];
	$scope.sensitiveInfoList = [];
	$scope.showDailyArr = [], $scope.showWeeklyArr = [], $scope.showMonthlyArr = [];
	$scope.moduleIdArr = [];
	$scope.moduleIdArr = moduleIds.split(',');
	$scope.menuArr = [];
	for(var i=0;i<$scope.moduleIdArr.length;i++){
		(function(i){
			$http.get(basePath + 'report/json/rpt'+rptCycleId+'moduleId'+$scope.moduleIdArr[i]+'.json').success(function(data){
				if(data.returnData){
					$scope.reportData[i] = data.returnData;
					if(rptCycleId==1){
						$scope.showDailyArr[i] = $scope.reportData[i].show;
						if($scope.reportData[i].dataList.length!=0){
							$scope.sensitiveInfoList[i] = $scope.reportData[i].dataList[0].datas;
						}
					}else if(rptCycleId==2){
						$scope.showWeeklyArr[i] = data.returnData.show;
						var dataList = data.returnData.dataList,
							dataArr = [],
							dataArr_type = [''];
						if($scope.moduleIdArr[i]==1||$scope.moduleIdArr[i]==5){
							if($scope.moduleIdArr[i]==5){
								for(var ii=0;ii<dataList.length;ii++){
									var bingTu = dataList[ii].datas;
									if(bingTu.length == 0) {
										dataArr.push(['暂无数据', 1]);
									} else {
										for(var j = 0; j < bingTu.length; j++) {
											if(dataList[ii].title) {
												var ptit = dataList[ii].title;
												ptit = ptit.length > 5 ? ptit.substr(0, 4) + '..' : ptit;
												dataArr.push([ptit, bingTu[j].firstNum - 0]);
											}
										}
									}
								}
								vm[$scope.reportData[i].id] = { //页面上，饼图的获取数据
									"type": ck_call(data),
									"title": $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: true,
										charttitle: $scope.reportData[i].name,
										type: 'pie',
										isShow: ck_call(data)
									},
									'data': {
										piedata: dataArr
									}
								}
							}
						}else{
							for(var ii=0; ii<dataList.length;ii++){
								dataArr_type.push(dataList[ii].title);
								var imgDatas = dataList[ii].datas;
								for(var j = 0; j < imgDatas.length; j++) {
									if(ii == 0) {
										dataArr.push({
											"xTime": time_month_day(imgDatas[j].time),
											"yCount": imgDatas[j].firstNum
										});
									} else {
										dataArr[j]["yCount" + ii] = imgDatas[j].firstNum;
									}
								}
							}
							if($scope.moduleIdArr[i]==11||$scope.moduleIdArr[i]==8){
								vm[$scope.reportData[i].id] = {
									'type': ck_call(data),
									'title': $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: true,
										charttitle: $scope.reportData[i].name,
										table: true,
										table_class: 'datatable',
										type: 'line',
										tablehide: true,
										isShow: ck_call(data)
									},
									'data': {
										table: {
											th: dataArr_type,
											td: dataArr
										}
									}
								};
							}else if($scope.moduleIdArr[i]==9||$scope.moduleIdArr[i]==10||$scope.moduleIdArr[i]==12){
								if($scope.moduleIdArr[i]==10){
									var ischart = false;
									var tablehide = false;
								}else{
									var ischart = true;
									var tablehide = true;
								}
								vm[$scope.reportData[i].id] = {
									'type': ck_call(data),
									'title': $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: ischart,
										charttitle: $scope.reportData[i].name,
										table: true,
										table_class: 'datatable',
										type: 'column',
										tablehide: tablehide,
										coltype: 0,
										isShow: ck_call(data)
									},
									'data': {
										table: {
											th: dataArr_type,
											td: dataArr
										}
									}
								};
							}
						}
					}else if(rptCycleId==3){
						$scope.showMonthlyArr[i] = $scope.reportData[i].show;
						var dataList = data.returnData.dataList,
							dataArr = [],
							dataArr_type = [''];
						if($scope.moduleIdArr[i]==1||$scope.moduleIdArr[i]==3||$scope.moduleIdArr[i]==4||$scope.moduleIdArr[i]==5){
							if($scope.moduleIdArr[i]==3||$scope.moduleIdArr[i]==4||$scope.moduleIdArr[i]==5){
								for(var ii=0;ii<dataList.length;ii++){
									var bingTu = dataList[ii].datas;
									if(bingTu.length == 0) {
										dataArr.push(['暂无数据', 1]);
									} else {
										for(var j = 0; j < bingTu.length; j++) {
											if(dataList[ii].title) {
												var ptit = dataList[ii].title;
												ptit = ptit.length > 5 ? ptit.substr(0, 4) + '...' : ptit;
												dataArr.push([ptit, bingTu[j].firstNum - 0]);
											}
										}
									}
								}
								vm[$scope.reportData[i].id] = { //页面上，饼图的获取数据
									"type": ck_call(data),
									"title": $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: true,
										charttitle: $scope.reportData[i].name,
										type: 'pie',
										isShow: ck_call(data)
									},
									'data': {
										piedata: dataArr
									}
								}
							}
						}else{
							if($scope.moduleIdArr[i]==2||$scope.moduleIdArr[i]==8){
								for(var ii=0; ii<dataList.length;ii++){
									dataArr_type.push(dataList[ii].title);
									var imgDatas = dataList[ii].datas;
									for(var j = 0; j < imgDatas.length; j++) {
										if(ii == 0) {
											dataArr.push({
												"xTime": time_month_day(imgDatas[j].time),
												"yCount": imgDatas[j].firstNum
											});
										} else {
											dataArr[j]["yCount" + ii] = imgDatas[j].firstNum;
										}
									}
								}
								vm[$scope.reportData[i].id] = {
									'type': ck_call(data),
									'title': $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: true,
										charttitle: $scope.reportData[i].name,
										table: true,
										table_class: 'datatable',
										type: 'line',
										tablehide: true,
										isShow: ck_call(data)
									},
									'data': {
										table: {
											th: dataArr_type,
											td: dataArr
										}
									}
								};
							}else if($scope.moduleIdArr[i]==7){
								dataArr_type = ["序号","首发媒体","标题","作者","转载量","发布时间"];
								for(var ii=0; ii<dataList.length;ii++){
									
									var tableDatas = dataList[ii].datas;
									for(var j = 0; j < tableDatas.length; j++) {
										var ptit = tableDatas[j].title;
										ptit = ptit.length > 19 ? ptit.substr(0, 18) + '...' : ptit;
										dataArr.push({
											"index": parseInt(j)+1,
											"sourceName": tableDatas[j].sourceName,
											"title": '<a href="'+tableDatas[j].url+'" target="_blank">'+ptit+'</a>',
											"author": tableDatas[j].author,
											"firstNum": tableDatas[j].firstNum,
											"time": tableDatas[j].time
										});
									}
								}
								vm[$scope.reportData[i].id] = {
									'type': ck_call(data),
									'title': $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: false,
										charttitle: $scope.reportData[i].name,
										table: true,
										table_class: 'datatable',
										type: 'column',
										tablehide: false,
										coltype: 0,
										isShow: ck_call(data)
									},
									'data': {
										table: {
											th: dataArr_type,
											td: dataArr
										}
									}
								};
							}else if($scope.moduleIdArr[i]==6){
								for(var ii=0; ii<dataList.length;ii++){
									dataArr_type.push(dataList[ii].title);
									var imgDatas = dataList[ii].datas;
									for(var j = 0; j < imgDatas.length; j++) {
										if(ii == 0) {
											dataArr.push({
												"xTime": imgDatas[j].sourceName,
												"yCount": imgDatas[j].firstNum
											});
										} else {
											dataArr[j]["yCount" + ii] = imgDatas[j].firstNum;
										}
									}
								}
								vm[$scope.reportData[i].id] = {
									'type': ck_call(data),
									'title': $scope.reportData[i].name + '&' + $scope.reportData[i].id,
									'opt': {
										ischart: true,
										charttitle: $scope.reportData[i].name,
										table: true,
										table_class: 'datatable',
										type: 'column',
										tablehide: true,
										coltype: 0,
										isShow: ck_call(data)
									},
									'data': {
										table: {
											th: dataArr_type,
											td: dataArr
										}
									}
								};
							}
						}
					}
				}
			});
		})(i);		
	}
	
	//快速到达页面顶部或底部
	$('.ht_fix .gt').click(function(){ 
		$('html,body').animate({'scrollTop':0}, 300);
	});
	$('.ht_fix .ge').click(function(){
		$('html,body').animate({'scrollTop':$('body').height()}, 300);
	});
});

app.filter('cut', function () {
	return function (value, wordwise, max, tail) {
		if (!value) return '';
		max = parseInt(max, 10);
		if (!max) return value;
		if (value.length <= max) return value;
		value = value.substr(0, max);
		if (wordwise) {
			var lastspace = value.lastIndexOf(' ');
			if (lastspace != -1) {
				value = value.substr(0, lastspace);
			}
		}
		return value + (tail || ' …');
	};
});

app.directive('chartS', function() {
	return {
		scope: {
			"data":"@",
			"opt": "@"
		},
		link: function($scope, element, attr) {
			$scope.$watch("opt", function() {
				try { //抛出异常？data或opt可能是个空对象？
					dof();
				} catch(e) {
	
				};
			});
			var dof = function() {
				var data = $.parseJSON(attr.data),
					opt = $.parseJSON(attr.opt),
					tableClass = opt.table_class || '';

				if(opt.isShow === false) {
					element.remove();
					return false;
				}

				if(opt.table) {
					var html = '<table class="' + opt.table_class + '">',
						th = '',
						td = '',
						j;
					for(var i = 0; i < data.table.th.length; i++) {
						var pw = data.table.th[i] == '标题' ? "width:30%" : "";
						th += '<th style="' + pw + '">' + data.table.th[i] + '</th>';
					};
					for(var i = 0; i < data.table.td.length; i++) {
						td += '<tr>';
						j = 0;
						for(key in data.table.td[i]) {
							if((j == 0) /*&& (opt.ischart)*/) {
								td += '<th>' + data.table.td[i][key] + '</th>';
							} else {
								td += '<td>' + data.table.td[i][key] + '</td>';
							}
							j++;
						}
						td += '</tr>';
					}
					html += '<tr>' + th + '</tr>' + td;
					html += "</table>";

//					if(opt.ischart) {
					html = "<div class='chartT'></div><div class='chart0_table'>" + html + "</div>"
//					}

				} else if(opt.ischart) {
					html = "<div class='chartT'></div>";
				}
				element.append(html);

				if(opt.ischart) {
					if(opt.xAxis_pid != undefined) {//除了0710和0713之外，其它opt.xAxis_pid均为undefined。
/*						if(opt.xAxis_pid == '0710') {
							if(opt.id_types == 2) {
								xAxis_ = {								
									min: 0,
									title: {
										text: '这里是x轴的内容：单位（日期）'
									}
								}
							}else{
								xAxis_ = {
									labels: {
										step: 1,
										formatter: function() {
											var arr = [];
											for(var i = 0; i <= 12; i++) {
												arr[i + '月1日'] = i + '月1日';
											}
											return arr[this.value]
										}
									}
								};							
							}
						}*/
					}else{
						xAxis_ = {}
					}

					if(opt.tablehide) {
						element.find('.datatable').hide();
					}
					if(opt.coltype == 0) {
						var column = {
							stacking: 'normal' //堆叠柱状图：normal表示正常堆叠，高度由数据决定。 percent表示所有柱子等高排放，每个柱子分布着不同的内容，内容高度按数据决定。
						}
					} else {
						var column = {
							pointPadding: 0.2,
							borderWidth: 0 ,  //柱子边框的大小
							pointWidth: 50  //设置柱状图宽度
						}
					}
					if(opt.type == 'pie') {
						/*var pradius = opt.type_rd || 1;*/
						if(data.piedata[0][0].search('暂无数据') > -1) {
							var vmformat = '<b>{point.name}</b>';
							var mscolor = ['#eeece1'];
							var vmpointFormat = '';
							/*pradius = 1;*/

						} else {
							var vmformat = '{point.name}{point.percentage:.0f} %';//'.2f'表示小数点后，保留2位
							var mscolor = colorS;
							var vmpointFormat = '{series.name}: <b>{point.percentage:.1f}%</b>';
						}
						element.find('.chartT').highcharts({
							chart: {
								plotBackgroundColor: null,
								plotBorderWidth: null,
								plotShadow: false,
								height: opt.new_height || 360,
								reflow: false
							},
							title: {
								text: opt.charttitle,
								align: 'left',
								floating: false,
								style: titleS
							},
							colors: mscolor,
							tooltip: {
								enabled: false
							},
							plotOptions: {
								pie: {
									allowPointSelect: true,//点击饼图的相应扇区会，将该扇区分离
									cursor: 'pointer',
									size: '80%',
									dataLabels: {
										enabled: true,
										color: '#000',
										style: {
											'fontSize': '14px'
										},
										distance: 20,//标注与饼图的距离
										format: vmformat
									},
									showInLegend: true
								}
							},
							legend: {//控制图例显示位置
					            layout: 'vertical',
					            align: 'right',
					            verticalAlign: 'bottom',
					            borderWidth: 0
					        },
							series: [{  //数据列
								type: opt.type,
								data: data.piedata
							}],
							credits: {
								enabled: false
							}
						});
					} else if((opt.type == 'spline') || (opt.type == 'line') || (opt.type == 'column') || (opt.type == 'bar') || (opt.type == "area")) {
						var _y = opt.charttitle.search('<br />') > -1 ? 35 : 15;
						if(opt.legend == 'hide') {
							legend = {
								enabled: false
							}
						} else {
							legend = {}
						}
						element.find('.chartT').highcharts({
							data: {
								table: element.find('.datatable')[0]
							},
							chart: {
								type: opt.type,
								backgroundColor: {	//曲线图的背景颜色的设置
									linearGradient: { //颜色的渐变: 从 linearGradient 到  stops 
										x1: 0,
										y1: 0,
										x2: 1,
										y2: 1
									},
									stops: [
										[0, '#fff'],
										[1, '#fff']
									]
								},
								plotBackgroundColor: '#fff', //主图表区背景色，即X轴与Y轴围成的区域的背景色
								plotShadow: false, //主图表区的边界阴影
								plotBorderWidth:1,
								reflow: false  //是否自使用图表区域高度和宽度，如果没有设置width和height时，会自适应大小。
							},
							colors: colorS,
							title: {
								text: opt.charttitle,
								align: 'left',
								style: titleS
							},
							subtitle: {
								text: '单位：条',
								align: 'right',
								floating: true,
								y: _y
							},
							xAxis: xAxis_,
							yAxis: {
								min: 0,
								title: {
									text: ''//这里是y轴的内容：单位（条）
								}
							},
							plotOptions: {
								line: {
									dataLabels: {
										enabled: true //是否允许数据标签
									},
									enableMouseTracking: true  //是否允许数据图表中，数据点的鼠标跟踪气泡显示
								},
								column: column
							},
							credits: {
								enabled: false  //显示版权的信息
							},
							legend: legend   //图标 显示形式，支持水平horizontal和垂直vertical
						});
					}
				}
			}
		}
	}
});

